package flc.ast.fragment;

import android.app.Dialog;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.blankj.utilcode.util.VolumeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.view.WheelView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import flc.ast.R;
import flc.ast.adapter.AudioAdapter;
import flc.ast.adapter.VoiceAdapter;
import flc.ast.bean.MyAudioBean;
import flc.ast.bean.VoiceBean;
import flc.ast.databinding.FragmentMusicBinding;
import flc.ast.utils.AudioPlayerImpl;
import in.xiandan.countdowntimer.CountDownTimerSupport;
import in.xiandan.countdowntimer.OnCountDownTimerListener;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.LogUtil;
import stark.common.basic.view.container.StkRecycleView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MusicFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MusicFragment extends BaseNoModelFragment<FragmentMusicBinding> {

    private AudioAdapter audioAdapter;
    private List<MyAudioBean> listAudio = new ArrayList<>();
    private boolean isMultiple = false;//多选
    private AudioPlayerImpl mAudioPlayer1, mAudioPlayer2, mAudioPlayer3, mAudioPlayer4, mAudioPlayer5;
    private int oldPosition;
    private List<MyAudioBean> listSel = new ArrayList<>();
    private boolean isPlay;//多选是否播放
    private Dialog mySelTimeDialog;
    private CountDownTimerSupport mTimer;//计时器
    private WheelView wheelView;
    private Dialog myVoiceDialog;
    private VoiceAdapter voiceAdapter;
    private float volume1 = 1.0f, volume2 = 1.0f, volume3 = 1.0f, volume4 = 1.0f, volume5 = 1.0f;


    @Override

    protected int onCreate() {
        return R.layout.fragment_music;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mAudioPlayer1 = new AudioPlayerImpl();
        mAudioPlayer1.setLoop(true);
        mAudioPlayer1.setHasLoop(true);

        mAudioPlayer2 = new AudioPlayerImpl();
        mAudioPlayer2.setLoop(true);
        mAudioPlayer2.setHasLoop(true);

        mAudioPlayer3 = new AudioPlayerImpl();
        mAudioPlayer3.setLoop(true);
        mAudioPlayer3.setHasLoop(true);

        mAudioPlayer4 = new AudioPlayerImpl();
        mAudioPlayer4.setLoop(true);
        mAudioPlayer4.setHasLoop(true);

        mAudioPlayer5 = new AudioPlayerImpl();
        mAudioPlayer5.setLoop(true);
        mAudioPlayer5.setHasLoop(true);

        mDataBinding.rvAudioList.setLayoutManager(new LinearLayoutManager(mContext));
        audioAdapter = new AudioAdapter();
        audioAdapter.setMultiple(isMultiple);
        mDataBinding.rvAudioList.setAdapter(audioAdapter);
        audioAdapter.setOnItemClickListener(this);

        mDataBinding.tvMultiple.setOnClickListener(this);
        mDataBinding.ivAudioPlay.setOnClickListener(this);
        mDataBinding.ivTiming.setOnClickListener(this);
        mDataBinding.ivVoice.setOnClickListener(this);

        voiceAdapter = new VoiceAdapter();

        //定时弹窗
        selTimeDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvMultiple://多选
                if (isMultiple) {
                    isMultiple = false;
                    stop();
                    listSel.clear();
                    isPlay = false;
                    mDataBinding.tvMultiple.setTextColor(Color.parseColor("#80FFFFFF"));
                    mDataBinding.ivAudioPlay.setImageResource(R.drawable.aicon_bf);
                    mDataBinding.ivAudioPlay.setVisibility(View.GONE);
                } else {
                    isMultiple = true;
                    stop();
                    listSel.clear();
                    audioAdapter.getItem(oldPosition).setPlaying(false);
                    audioAdapter.notifyItemChanged(oldPosition);
                    mDataBinding.tvMultiple.setTextColor(Color.parseColor("#B7EF4F"));
                    mDataBinding.ivAudioPlay.setVisibility(View.VISIBLE);
                }
                audioAdapter.setMultiple(isMultiple);
                audioAdapter.notifyDataSetChanged();
                break;
            case R.id.ivAudioPlay://播放
                stop();
                if (isPlay) {
                    mDataBinding.ivAudioPlay.setImageResource(R.drawable.aicon_bf);
                } else {
                    mDataBinding.ivAudioPlay.setImageResource(R.drawable.aicon_zt);
                    if (listSel.size() >= 1) {
                        play(listSel.get(0).getMusic(), mAudioPlayer1);
                    }
                    if (listSel.size() >= 2) {
                        play(listSel.get(1).getMusic(), mAudioPlayer2);
                    }
                    if (listSel.size() >= 3) {
                        play(listSel.get(2).getMusic(), mAudioPlayer3);
                    }
                    if (listSel.size() >= 4) {
                        play(listSel.get(3).getMusic(), mAudioPlayer4);
                    }
                    if (listSel.size() >= 5) {
                        play(listSel.get(4).getMusic(), mAudioPlayer5);
                    }
                }
                isPlay = !isPlay;
                break;
            case R.id.ivTiming://定时
                mySelTimeDialog.show();
                break;
            //定时弹窗
            case R.id.tvSelTimeCancel://取消
                mySelTimeDialog.dismiss();
                break;
            case R.id.tvSelTimeConfirm://确定
                int pos = wheelView.getCurrentItem();
                long time = pos * 3600000;
                mTimer = new CountDownTimerSupport(time, 1000);
                mTimer.setOnCountDownTimerListener(new OnCountDownTimerListener() {
                    @Override
                    public void onTick(long millisUntilFinished) {

                    }

                    @Override
                    public void onFinish() {
                        // 倒计时结束
                        if (mAudioPlayer1 != null) {
                            mAudioPlayer1.stop();
                        }
                        if (mAudioPlayer2 != null) {
                            mAudioPlayer2.stop();
                        }
                        if (mAudioPlayer3 != null) {
                            mAudioPlayer3.stop();
                        }
                        if (mAudioPlayer4 != null) {
                            mAudioPlayer4.stop();
                        }
                        if (mAudioPlayer5 != null) {
                            mAudioPlayer5.stop();
                        }
                        mDataBinding.ivAudioPlay.setImageResource(R.drawable.aicon_bf);
                        audioAdapter.getItem(oldPosition).setPlaying(false);
                        audioAdapter.notifyItemChanged(oldPosition);
                        ToastUtils.showShort(getString(R.string.timing_suc));
                    }

                    @Override
                    public void onCancel() {
                        // 倒计时手动停止
                    }
                });
                mTimer.start();
                mySelTimeDialog.dismiss();
                break;
            case R.id.ivVoice://声音调节
                if (listSel.size() == 0) {
                    ToastUtils.showShort(getString(R.string.not_play_audio));
                    return;
                }
                //音量弹窗
                voiceDialog();
                myVoiceDialog.show();
                break;
            //音量弹框
            case R.id.tvVoiceCancel://取消
                myVoiceDialog.dismiss();
                break;
            case R.id.tvVoiceConfirm://确定
                if (listSel.size() >= 1) {
                    volume1 = voiceAdapter.getItem(0).getVolume();
                    mAudioPlayer1.setVolume(volume1);
                }
                if (listSel.size() >= 2) {
                    volume2 = voiceAdapter.getItem(1).getVolume();
                    mAudioPlayer2.setVolume(volume2);
                }
                if (listSel.size() >= 3) {
                    volume3 = voiceAdapter.getItem(2).getVolume();
                    mAudioPlayer3.setVolume(volume3);
                }
                if (listSel.size() >= 4) {
                    volume4 = voiceAdapter.getItem(3).getVolume();
                    mAudioPlayer4.setVolume(volume4);
                }
                if (listSel.size() >= 5) {
                    volume5 = voiceAdapter.getItem(4).getVolume();
                    mAudioPlayer5.setVolume(volume5);
                }
                myVoiceDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isMultiple) {
            if (audioAdapter.getItem(position).isSelected()) {
                audioAdapter.getItem(position).setSelected(false);
                listSel.remove(audioAdapter.getItem(position));
            } else {
                if (listSel.size() >= 5) {
                    ToastUtils.showShort(getString(R.string.is_max_sel));
                    return;
                }
                listSel.add(audioAdapter.getItem(position));
                audioAdapter.getItem(position).setSelected(true);
            }
            audioAdapter.notifyItemChanged(position);
        } else {
            listSel.clear();
            listSel.add(audioAdapter.getItem(position));

            audioAdapter.getItem(oldPosition).setPlaying(false);
            audioAdapter.notifyItemChanged(oldPosition);
            oldPosition = position;
            audioAdapter.getItem(position).setPlaying(true);
            audioAdapter.notifyItemChanged(position);
            play(audioAdapter.getItem(position).getMusic(), mAudioPlayer1);
        }
    }

    @Override
    protected void initData() {
        //治愈音乐
        Integer[] tag1 = {R.drawable.aazhumian, R.drawable.aahaishan};
        Integer[] tag2 = {R.drawable.aazhumian};
        Integer[] tag3 = {R.drawable.aashimian, R.drawable.aashuhuan};
        Integer[] tag4 = {R.drawable.aahaishan};
        Integer[] tag5 = {R.drawable.aazhiyu, R.drawable.aaqinying};
        Integer[] tag6 = {R.drawable.aazhumian};
        Integer[] tag7 = {R.drawable.aashuhuan};
        Integer[] tag8 = {R.drawable.aashimian, R.drawable.aashuhuan};
        listAudio.add(new MyAudioBean(R.drawable.aa1, getString(R.string.cure_text1), tag1, TimeUtils.millis2String(getRawFileVoiceTime(R.raw.music1), "mm:ss"), R.raw.music1, false, false));
        listAudio.add(new MyAudioBean(R.drawable.aa2, getString(R.string.cure_text2), tag2, TimeUtils.millis2String(getRawFileVoiceTime(R.raw.music2), "mm:ss"), R.raw.music2, false, false));
        listAudio.add(new MyAudioBean(R.drawable.aa3, getString(R.string.cure_text3), tag3, TimeUtils.millis2String(getRawFileVoiceTime(R.raw.music3), "mm:ss"), R.raw.music3, false, false));
        listAudio.add(new MyAudioBean(R.drawable.aa4, getString(R.string.cure_text4), tag4, TimeUtils.millis2String(getRawFileVoiceTime(R.raw.music4), "mm:ss"), R.raw.music4, false, false));
        listAudio.add(new MyAudioBean(R.drawable.aa5, getString(R.string.cure_text5), tag5, TimeUtils.millis2String(getRawFileVoiceTime(R.raw.music5), "mm:ss"), R.raw.music5, false, false));
        listAudio.add(new MyAudioBean(R.drawable.aa6, getString(R.string.cure_text6), tag6, TimeUtils.millis2String(getRawFileVoiceTime(R.raw.music6), "mm:ss"), R.raw.music6, false, false));
        listAudio.add(new MyAudioBean(R.drawable.aa7, getString(R.string.cure_text7), tag7, TimeUtils.millis2String(getRawFileVoiceTime(R.raw.music7), "mm:ss"), R.raw.music7, false, false));
        listAudio.add(new MyAudioBean(R.drawable.aa8, getString(R.string.cure_text8), tag8, TimeUtils.millis2String(getRawFileVoiceTime(R.raw.music8), "mm:ss"), R.raw.music8, false, false));
        audioAdapter.setList(listAudio);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            stop();
            isPlay = false;
            mDataBinding.ivAudioPlay.setImageResource(R.drawable.aicon_bf);
            audioAdapter.getItem(oldPosition).setPlaying(false);
            audioAdapter.notifyItemChanged(oldPosition);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mAudioPlayer1 != null) {
            mAudioPlayer1.stop();
        }
        if (mAudioPlayer2 != null) {
            mAudioPlayer2.stop();
        }
        if (mAudioPlayer3 != null) {
            mAudioPlayer3.stop();
        }
        if (mAudioPlayer4 != null) {
            mAudioPlayer4.stop();
        }
        if (mAudioPlayer5 != null) {
            mAudioPlayer5.stop();
        }
    }

    private void play(Integer path, AudioPlayerImpl audioPlayer) {
        Uri uri = Uri.parse("android.resource://" + AppUtils.getAppPackageName() + "/" + path);
        audioPlayer.play(UriUtils.uri2File(uri).getPath());
    }

    private void stop() {
        mAudioPlayer1.pause();
        mAudioPlayer2.pause();
        mAudioPlayer3.pause();
        mAudioPlayer4.pause();
        mAudioPlayer5.pause();
    }

    public long getRawFileVoiceTime(int rawId) {
        long mediaPlayerDuration = 0L;
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            Uri uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + rawId);
            mediaPlayer.setDataSource(mContext, uri);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepare();
            mediaPlayerDuration = mediaPlayer.getDuration();
        } catch (Exception exception) {
            LogUtil.i("TAG", exception.getMessage());
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
        }
        return mediaPlayerDuration;
    }

    //定时弹窗
    private void selTimeDialog() {
        mySelTimeDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_time, null);
        mySelTimeDialog.setContentView(inflate);
        mySelTimeDialog.setCancelable(true);
        Window dialogWindow = mySelTimeDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvSelTimeCancel);
        TextView confirm = inflate.findViewById(R.id.tvSelTimeConfirm);
        wheelView = inflate.findViewById(R.id.wvSelTime);
        wheelView.setDividerColor(Color.parseColor("#070707"));
        wheelView.setTextColorCenter(Color.parseColor("#FFFFFF"));
        wheelView.setLineSpacingMultiplier(2.5f);
        wheelView.setDividerType(WheelView.DividerType.WRAP);
        wheelView.setTextSize(40);
        wheelView.setCurrentItem(0);
        wheelView.setLineSpacingMultiplier(1.4f);
        wheelView.setItemsVisibleCount(3);
        wheelView.setCyclic(true);
        List<String> list = Arrays.asList(getResources().getStringArray(R.array.sel_time));
        WheelAdapter adapter = new ArrayWheelAdapter(list);
        wheelView.setAdapter(adapter);

        cancel.setOnClickListener(this);
        confirm.setOnClickListener(this);
    }

    //音量弹窗
    private void voiceDialog() {
        myVoiceDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_voice, null);
        myVoiceDialog.setContentView(inflate);
        myVoiceDialog.setCancelable(true);
        Window dialogWindow = myVoiceDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvVoiceCancel);
        TextView confirm = inflate.findViewById(R.id.tvVoiceConfirm);
        StkRecycleView stkRecycleView = inflate.findViewById(R.id.rvVoiceList);
        stkRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        stkRecycleView.setAdapter(voiceAdapter);

        List<VoiceBean> list = new ArrayList<>();
        if (listSel.size() >= 1) {
            list.add(new VoiceBean(listSel.get(0).getIcon(), mAudioPlayer1, volume1));
        }
        if (listSel.size() >= 2) {
            list.add(new VoiceBean(listSel.get(1).getIcon(), mAudioPlayer2, volume2));
        }
        if (listSel.size() >= 3) {
            list.add(new VoiceBean(listSel.get(2).getIcon(), mAudioPlayer3, volume3));
        }
        if (listSel.size() >= 4) {
            list.add(new VoiceBean(listSel.get(3).getIcon(), mAudioPlayer4, volume4));
        }
        if (listSel.size() >= 5) {
            list.add(new VoiceBean(listSel.get(4).getIcon(), mAudioPlayer5, volume5));
        }
        voiceAdapter.setList(list);

        cancel.setOnClickListener(this);
        confirm.setOnClickListener(this);
    }


}